// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'changeSpanContent') {
    changeSpanContent(request.selector, request.newContent, request.replaceMode, request.selectorType, request.originalSelector);
    
    // 发送响应
    sendResponse({
      success: true,
      changedCount: window.changedCount || 0
    });
  }
  return true; // 保持消息通道开放
});

// 添加contains选择器支持（如果浏览器不支持）
if (!document.querySelectorAll(':contains("test")').length) {
  const originalQuerySelectorAll = document.querySelectorAll;
  document.querySelectorAll = function(selector) {
    if (selector.includes(':contains(')) {
      const match = selector.match(/(.*):contains\("([^"]*)"\)/);
      if (match) {
        const baseSelector = match[1] || '*';
        const searchText = match[2];
        const allElements = originalQuerySelectorAll.call(document, baseSelector);
        const filtered = Array.from(allElements).filter(el => 
          el.textContent.includes(searchText)
        );
        return filtered;
      }
    }
    return originalQuerySelectorAll.call(document, selector);
  };
}

function changeSpanContent(selector, newContent, replaceMode, selectorType, originalSelector) {
  let spans;
  let changedCount = 0;
  
  try {
    // 根据选择器类型选择元素
    if (selectorType === 'text') {
      // 对于文本匹配，我们使用自定义的contains逻辑
      spans = Array.from(document.querySelectorAll('span')).filter(span => 
        span.textContent.includes(originalSelector)
      );
    } else {
      spans = document.querySelectorAll(selector);
    }
    
    if (!spans.length) {
      sendResponseToPopup('未找到匹配的span元素', 0);
      return;
    }
    
    // 根据模式替换内容
    if (replaceMode === 'first') {
      spans = [spans[0]];
    }
    
    spans.forEach(span => {
      if (selectorType === 'text') {
        // 对于文本匹配，替换匹配的文本部分
        const newText = span.textContent.replace(originalSelector, newContent);
        span.textContent = newText;
      } else {
        // 对于其他选择器，直接替换整个内容
        span.textContent = newContent;
      }
      changedCount++;
    });
    
    window.changedCount = changedCount;
    console.log(`成功更改了 ${changedCount} 个span元素`);
    
  } catch (error) {
    console.error('更改span内容时出错:', error);
    sendResponseToPopup('执行出错: ' + error.message, 0);
  }
}

function sendResponseToPopup(message, count) {
  // 这里可以通过chrome.runtime.sendMessage发送响应
  // 或者在changeSpanContent被调用时直接返回结果
}